package com.zzyl.intercept;

import com.alibaba.fastjson.JSONObject;
import com.zzyl.base.BaseVo;
import com.zzyl.constant.Constants;
import com.zzyl.constant.JwtClaimsConstant;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    JwtProperties jwtProperties;

    /**
     * 校验JWT
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("客户端拦截器: {}",request.getRequestURI());
        String token = request.getHeader(jwtProperties.getTokenName());
        // 校验令牌
        try {
            // 从请求头中获取令牌
            log.info("jwt校验: {}", Constants.TOKEN);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id :{}",userId);
            BaseVo baseVo = new BaseVo();
            baseVo.setId(userId);
            String jsonString = JSONObject.toJSONString(baseVo);
            UserThreadLocal.setSubject(jsonString);
            // 通过,放行
            return true;
        } catch (Exception e) {
            // 不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 释放资源
        UserThreadLocal.removeSubject();
    }
}
